package cn.ittaoli.utils;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by lub_lenovo on 2017/11/3.
 */
public class FileUpload {
    public static String upload(MultipartFile file, HttpServletRequest request) throws IOException {
        //文件上传的upload文件夹的绝对路径
        String path = request.getSession().getServletContext().getRealPath("upload");
        //文件夹下面添加二级目录，按照日期添加
        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        String date=format1.format(new Date());//2017-08-08
        //设置路径为 upload+date，如：/upload/2017-08-08/
        path+="/"+date;
//        文件原始名称
        String fileName = file.getOriginalFilename();
//        文件名的后缀
        String ext=fileName.substring(fileName.lastIndexOf('.'));
//        新文件名称
//        fileName=String.valueOf(System.currentTimeMillis())+ext;
        fileName= IDUtils.genImageName()+ext;

        File dir = new File(path,fileName);

        if(!dir.exists()){
            dir.mkdirs();
        }

        //MultipartFile自带的解析方法
        file.transferTo(dir);
        return request.getContextPath()+"/upload/"+date+"/"+fileName;
    }
}